<template>
  <div class="admin-media-info">
    <div class="page-header">
      <h2>媒体信息</h2>
      <div class="header-actions">
        <el-button type="primary" @click="openEdit()"><el-icon><Plus /></el-icon>新增媒体</el-button>
      </div>
    </div>

    <el-card>
      <div class="toolbar">
        <el-input v-model="keyword" placeholder="搜索媒体名称/联系人" style="width: 240px" clearable />
        <el-select v-model="status" placeholder="状态" clearable style="width: 140px">
          <el-option label="启用" value="active" />
          <el-option label="禁用" value="inactive" />
        </el-select>
        <el-button @click="loadList" :loading="loading">查询</el-button>
        <el-button @click="exportExcel">导出</el-button>
      </div>

      <el-table :data="list" v-loading="loading" stripe>
        <el-table-column prop="mediaName" label="媒体名称" min-width="180" />
        <el-table-column prop="mediaType" label="类型" width="120" />
        <el-table-column prop="contactPerson" label="联系人" width="140" />
        <el-table-column prop="contactPhone" label="电话" width="140" />
        <el-table-column prop="contactEmail" label="邮箱" width="180" />
        <el-table-column prop="accreditationStatus" label="认证状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.accreditationStatus==='approved'?'success':(scope.row.accreditationStatus==='rejected'?'danger':'warning')">
              {{ scope.row.accreditationStatus || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status==='active'?'success':'info'">{{ scope.row.status==='active'?'启用':'禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown>
              <el-button size="small" type="primary">
                审核
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleAccredit(scope.row,'approved')">通过</el-dropdown-item>
                  <el-dropdown-item @click="handleAccredit(scope.row,'rejected')">拒绝</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="size"
          :total="total"
          :current-page="current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="form.id?'编辑媒体':'新增媒体'" width="700px">
      <el-form :model="form" label-width="110px" ref="formRef">
        <el-form-item label="媒体名称" required>
          <el-input v-model="form.mediaName" />
        </el-form-item>
        <el-form-item label="媒体类型">
          <el-select v-model="form.mediaType" placeholder="请选择">
            <el-option label="报纸" value="newspaper" />
            <el-option label="杂志" value="magazine" />
            <el-option label="电视" value="tv" />
            <el-option label="广播" value="radio" />
            <el-option label="网络" value="online" />
            <el-option label="社交媒体" value="social" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="form.contactPerson" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="form.contactPhone" />
        </el-form-item>
        <el-form-item label="联系邮箱">
          <el-input v-model="form.contactEmail" />
        </el-form-item>
        <el-form-item label="官方网站">
          <el-input v-model="form.website" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="媒体简介">
          <el-input type="textarea" :rows="3" v-model="form.description" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowDown } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useExcelExport } from '@/hooks/useExcelExport'

export default {
  name: 'AdminMediaInfo',
  components: { Plus, ArrowDown },
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const list = ref([])
    const total = ref(0)
    const current = ref(1)
    const size = ref(10)
    const keyword = ref('')
    const status = ref('')

    // 使用Excel导出hooks
    const { exportListData, columnWidthPresets, mapperPresets } = useExcelExport()

    const dialogVisible = ref(false)
    const formRef = ref(null)
    const form = reactive({
      id: null,
      mediaName: '',
      mediaType: '',
      contactPerson: '',
      contactPhone: '',
      contactEmail: '',
      website: '',
      address: '',
      description: '',
      status: 'inactive'
    })

    const loadList = async () => {
      loading.value = true
      try {
        const params = { current: current.value, size: size.value }
        if (status.value) params.status = status.value
        if (keyword.value) params.keyword = keyword.value
        const res = await request.get('/admin/media/page', { params })
        if (res && (res.code === '200' || res.code === 200)) {
          const data = res.data || {}
          list.value = data.records || []
          total.value = data.total || 0
        }
      } catch (e) {
        ElMessage.error('加载失败')
      } finally {
        loading.value = false
      }
    }

    const openEdit = (row) => {
      if (row) {
        Object.assign(form, row)
      } else {
        Object.assign(form, { id: null, mediaName: '', mediaType: '', contactPerson: '', contactPhone: '', contactEmail: '', website: '', address: '', description: '', status: 'inactive' })
      }
      dialogVisible.value = true
    }

    const handleSave = async () => {
      saving.value = true
      try {
        const api = form.id ? request.put : request.post
        const url = '/admin/media' + (form.id ? '' : '')
        const res = await api(url, { ...form })
        if (res && (res.code === '200' || res.code === 200)) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          await loadList()
        } else {
          ElMessage.error(res?.msg || '保存失败')
        }
      } catch (e) {
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确定删除“${row.mediaName}”吗？`, '确认', { type: 'warning' })
        const res = await request.delete(`/admin/media/${row.id}`)
        if (res && (res.code === '200' || res.code === 200)) {
          ElMessage.success('删除成功')
          await loadList()
        } else {
          ElMessage.error(res?.msg || '删除失败')
        }
      } catch {}
    }

    const handleAccredit = async (row, accreditationStatus) => {
      try {
        const res = await request.put(`/admin/media/${row.id}/accredit`, null, { params: { accreditationStatus, auditUser: 'admin' } })
        if (res && (res.code === '200' || res.code === 200)) {
          ElMessage.success('审核成功')
          await loadList()
        } else {
          ElMessage.error(res?.msg || '审核失败')
        }
      } catch (e) {
        ElMessage.error('审核失败')
      }
    }

    const handleSizeChange = (newSize) => {
      size.value = newSize
      current.value = 1 // 重置到第一页
      loadList()
    }
    
    const handleCurrentChange = (newCurrent) => {
      current.value = newCurrent
      loadList()
    }

    // 导出媒体信息列表
    const exportExcel = async () => {
      // 获取数据的函数
      const fetchData = async () => {
        const params = { current: 1, size: 100000 }
        if (status.value) params.status = status.value
        if (keyword.value) params.keyword = keyword.value
        const res = await request.get('/admin/media/page', { params })
        return res.data?.records || []
      }

      // 数据映射函数，对应媒体信息表单中的字段
      const mapData = (item) => ({
        '媒体名称': mapperPresets.handleEmpty(item.mediaName),
        '媒体类型': getMediaTypeText(item.mediaType),
        '联系人': mapperPresets.handleEmpty(item.contactPerson),
        '联系电话': mapperPresets.handleEmpty(item.contactPhone),
        '联系邮箱': mapperPresets.handleEmpty(item.contactEmail),
        '官方网站': mapperPresets.handleEmpty(item.website),
        '地址': mapperPresets.handleEmpty(item.address),
        '媒体简介': mapperPresets.handleEmpty(item.description),
        '认证状态': getAccreditationStatusText(item.accreditationStatus),
        '状态': item.status === 'active' ? '启用' : '禁用'
      })

      // 自定义媒体信息列表的列宽
      const mediaColumnWidths = [
        { wch: 25 }, // 媒体名称
        { wch: 15 }, // 媒体类型
        { wch: 15 }, // 联系人
        { wch: 15 }, // 联系电话
        { wch: 25 }, // 联系邮箱
        { wch: 30 }, // 官方网站
        { wch: 30 }, // 地址
        { wch: 40 }, // 媒体简介
        { wch: 12 }, // 认证状态
        { wch: 10 }  // 状态
      ]

      // 使用hooks进行导出
      await exportListData(
        fetchData,
        mapData,
        '媒体信息列表',
        mediaColumnWidths,
        '媒体信息列表'
      )
    }

    // 获取媒体类型文本
    const getMediaTypeText = (type) => {
      const typeMap = {
        'newspaper': '报纸',
        'magazine': '杂志',
        'tv': '电视',
        'radio': '广播',
        'online': '网络',
        'social': '社交媒体'
      }
      return typeMap[type] || mapperPresets.handleEmpty(type)
    }

    // 获取认证状态文本
    const getAccreditationStatusText = (status) => {
      const statusMap = {
        'approved': '已通过',
        'rejected': '已拒绝',
        'pending': '待审核'
      }
      return statusMap[status] || mapperPresets.handleEmpty(status)
    }

    onMounted(loadList)

    return { loading, saving, list, total, current, size, keyword, status, dialogVisible, formRef, form, loadList, openEdit, handleSave, handleDelete, handleAccredit, handleSizeChange, handleCurrentChange, exportExcel }
  }
}
</script>

<style scoped>
.admin-media-info { padding: 20px; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.toolbar { display: flex; gap: 10px; margin-bottom: 12px; }
.pager { margin-top: 12px; display: flex; justify-content: flex-end; }
</style>


